import express from 'express'
import partials from 'express-partials'
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
import createError from 'http-errors'
import history from 'connect-history-api-fallback'
import compression from 'compression'

import locals from'./middlewares/locals'
import { apis, pages } from './routes'
import { consts, utils } from './common'

const app = express()
const { BASE_PATH, ASSET_PATH, ASSET_DIR } = consts

// 模板引擎设置
app.set('views', utils.pathJoin('views'));
app.set('view engine', 'ejs');

// 解析静态文件路径
app.use(locals())

// 压缩文件
app.use(compression())
app.use(partials())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use(cookieParser())

// ================ START =================
// 1、路由：跳转首页
if (BASE_PATH && BASE_PATH !== '/') {
  app.get('', function (_, res) {
    res.redirect(BASE_PATH)
  })
}

// 2、路由：静态文件
if (utils.isProd(app)) {
  // 生产环境：提供静态文件路由

  app.use(
    ASSET_PATH,
    express.static(utils.pathJoin('..', ASSET_DIR), {
      maxAge: 0, // a month
    })
  )
} else {
  // 开发环境：前端资源代理到webpack-dev-server

  const { createProxyMiddleware } = require('http-proxy-middleware')
  app.use(
    ASSET_PATH,
    createProxyMiddleware({
      target: 'http://localhost:8001',
      pathRewrite: { [`^${consts.ASSET_PATH}`]: '/public' },
    })
  )
}

// 3、路由：路由中间件，防止刷新URL出现404
app.use(
  history({
    index: BASE_PATH,
    // verbose: true,
    disableDotRule: true,
  })
)
// ================ END =================

// 路由：页面
app.use(BASE_PATH, pages())
// 路由：数据API
app.use('/api', apis())

// 404错误页面
app.use(function(req, res, next) {
  next(createError(404));
});

// 500错误页面
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
